<?php
function read_csv($file)
{
    setlocale(LC_ALL,'zh_CN');//linux系统下生效
    $data = null;//返回的文件数据行
    if(!is_file($file)&&!file_exists($file))
    {
        die('文件错误');
    }
    $cvs_file = fopen($file,'r'); //开始读取csv文件数据
    $i = 0;//记录cvs的行
    while ($file_data = fgetcsv($cvs_file))
    {
        $i++;
        if($i==1)
        {
            continue;//过滤表头
        }
        if($file_data[0]!='')
        {
            $data[$i] = $file_data;
        }
 
    }
    fclose($cvs_file);
    return $data;
}

function createcsv($csv_body,$csv_header)
{
    // 头部标题
    $csv_header = array('Price','SKU');

    /**
     * 开始生成
     * 1. 首先将数组拆分成以逗号（注意需要英文）分割的字符串
     * 2. 然后加上每行的换行符号，这里建议直接使用PHP的预定义
     * 常量PHP_EOL
     * 3. 最后写入文件
     */
// 打开文件资源，不存在则创建
    $des_file = './res.csv';
    $fp = fopen(    $des_file,'a');
// 处理头部标题
    $header = implode(',', $csv_header) . PHP_EOL;
// 处理内容
    $content = '';
    foreach ($csv_body as $k => $v) {
        $content .= implode(',', $v) . PHP_EOL;
    }
// 拼接
    $csv = $header.$content;
// 写入并关闭资源
    fwrite($fp, $csv);
    fclose($fp);
}

//尾数处理
function endPriceFormat($price,$endprice)
{
	$end_length = strlen("$endprice");
	$point_end_length = strlen(strrchr("$endprice", '.'));
	if($point_end_length>0){
		$price = sprintf('%.'.($point_end_length-1).'f',$price);
	}else{
		$price = sprintf('%.0f',$price);
	}
	
	return substr_replace($price,$endprice,-$end_length);
}


$aim_sku = read_csv('./shopify_all.csv');
$aim_sku_list = [];
$aim_data_by_sku = [];
foreach($aim_sku as $key1=>$value1){
    $aim_sku_list[] = $value1[1];
    if(isset($aim_data_by_sku[$value1[1]])){
        echo $value1[1].',';
    }
    $aim_data_by_sku[$value1[1]] = $value1;

//    echo $value1[0].",".$value1[1].';';
}
$data = read_csv('./price_2.csv');
$csv_data = [];
$pack_sku = [];

$endprice = 9.99;
$multiple = 1.4;

foreach ($data as $key => $value) {
	// echo $value[0].','.$value[1].'<br>';
	$_sku = explode('-', $value[0]);
	$_is_pack = count($_sku)-1;
	$sku = $_sku[0];
	if($_is_pack){
		if(!isset($pack_sku[$sku]))
			$pack_sku[$sku] = 0;
		$pack_sku[$sku] = $pack_sku[$sku]+(float)$value[1];

	}else{
		//update
	    $sale_price = endPriceFormat($value[1]*$multiple,$endprice);
        //echo 'sku:'.$key.',cost of:'.$value.',sale price:'.$sale_price.'<br>';
        if(in_array($sku, $aim_sku_list)){
            $aim_data_by_sku[$sku] = [$sale_price,$sku];
        }
    }
}


foreach ($pack_sku as $key => $value) {
	$sale_price = endPriceFormat($value*$multiple,$endprice);
	//echo 'sku:'.$key.',cost of:'.$value.',sale price:'.$sale_price.'<br>';
    $sku = $key;
    if(in_array($sku, $aim_sku_list)){
        $aim_data_by_sku[$sku] = [$sale_price,$sku];
    }
}
foreach($aim_data_by_sku as $key1=>$value1){
    //echo $value1[0].",".$value1[1].';';
}
//var_dump($csv_body);
//createcsv($aim_data_by_sku,[]);